import { resolve } from 'node:path'

import { customHtml } from '@ttou/vite-html'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import components from 'unplugin-vue-components/vite'
import { CommonServerOptions, defineConfig, loadEnv } from 'vite'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, '.')
  const commonServerOptions: CommonServerOptions = {
    port: 7002,
    host: true
  }

  return {
    css: {
      modules: {
        generateScopedName: '[local]__[hash:base64:5]'
      }
    },
    define: {
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
    },
    resolve: {
      alias: [
        {
          find: '@/',
          replacement: `${resolve(__dirname, 'src')}/`
        },
        ...(mode === 'production'
          ? [
              {
                find: 'vue-types',
                replacement: 'vue-types/shim'
              }
            ]
          : [])
      ]
    },
    plugins: [
      vueJsx(),
      components({
        dts: false,
        dirs: [],
        resolvers: [
          ElementPlusResolver({
            importStyle: false
          })
        ]
      }),
      customHtml({
        injectTitle: `<title>${env.VITE_APP_TITLE}</title>`
      })
    ],
    optimizeDeps: {
      include: ['dayjs/locale/zh-cn']
    },
    server: {
      ...commonServerOptions
    },
    build: {
      chunkSizeWarningLimit: 2048,
      reportCompressedSize: false,
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks: {
            vue: [
              'vue',
              'vue-router',
              'vue-types',
              'pinia',
              '@vueuse/core',
              '@vueuse/integrations'
            ],
            iconify: [
              '@iconify-json/ep',
              '@iconify-json/icon-park-outline',
              '@iconify/vue'
            ],
            'element-plus': ['element-plus'],
            'vxe-table': ['vxe-table', 'vxe-table-plugin-element', 'xe-utils']
          }
        }
      }
    }
  }
})
